package com.jia.config;

import com.alibaba.fastjson2.JSON;
import com.jia.entity.User;
import com.jia.service.UserService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

//@Component
public class CustomRabbitMq {


    //转换成集合
    private List<User> users =null;

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    /**
     * 生产者发送到需要退还押金的申请信息
     * 消费者进行接收使用消费者确认模式 ack
     * 确认成功之后删除消息同步到数据库中
     * 确认失败返回消息到队列中 或者丢弃
     * @param message
     */
    @RabbitListener(queues = "deposit_queue")
    public void getMessage(Message message, Channel channel) {
        System.out.println("接收到消息为:"+message);
        try {
            //转换成集合
             users = JSON.parseArray(message.getBody(), User.class);

            users.forEach(System.err::println);

            System.out.println("签收");

            //确认签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);

        } catch (Exception e) {
            e.printStackTrace();
            try {
                //拒绝签收
                System.out.println("拒绝签收");
                //保证消息不丢失，要么重新回到队列，要么变成死信，发送到死信队列中
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,true);
            } catch (IOException ex) {
                e.printStackTrace();
            }
        }
    }
}
